import { ElMessage, ElLoading } from 'element-plus'
import { blobValidate } from "@/utils/tool"
import { saveAs } from 'file-saver'
import request from '@/utils/request'
import { utils, read, writeFile } from 'xlsx'
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_URL

let downloadLoadingInstance
// 通用下载方法
export function download (params, filename) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return request({
    // url: '/fileOperation/downloadFile',
    // method: 'get',
    // params: params,
    baseURL: uploadUrl,
    url: `/downloadFile`,
    method: 'get',
    params,
    responseType: 'blob'
  }).then(async ({ data }) => {
    // console.log('data', data)
    const isBlob = blobValidate(data)
    // console.log('blob', isBlob, filename)
    if (isBlob)
    {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else
    {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = rspObj.msg || '系统未知错误，请反馈给管理员'
      ElMessage.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    ElMessage.error(r.message)
    downloadLoadingInstance.close()
  })
}

// 通用导出列表方法
// exsample

// let _data = [
//   {
//       a: 'aaa1',
//       b: 'bbb1',
//       c: 'ccc1',
//       d: 'ddd1',
//   },
//   {
//       a: 'aaa2',
//       b: 'bbb2',
//       c: 'ccc2',
//       d: 'ddd2',
//   },
//   {
//       a: 'aaa3',
//       b: 'bbb3',
//       c: 'ccc3',
//       d: 'ddd3',
//   }
// ]
// let _keys = [
//   'a',
//   'b',
//   'd'
// ]
// let _names = [
//   '表头a',
//   '表头b',
//   '表头d',
// ]
export function exportTableToExcel (dataList, dataKey, firstRowNames, filename) {
  const workBook = utils.book_new()
  const handledDataList = dataList.map(data => dataKey.map(key => data[key]))
  handledDataList.unshift(firstRowNames)
  const sheet = utils.aoa_to_sheet(handledDataList)
  dataKey.forEach((key, index) => {
    // 设置列宽与列中最长字符串的长度成比例
    let maxWidth = 0
    for (let i = 0; i < handledDataList.length; i++)
    {
      const cellValue = handledDataList[i][index] ? `${handledDataList[i][index]}`.toString() : ''
      if (cellValue.length > maxWidth)
      {
        maxWidth = cellValue.length
      }
    }
    // 设置列宽
    const colWidth = maxWidth < 50 ? Math.max(maxWidth, 10) : 50
    sheet['!cols'] = sheet['!cols'] || []
    if (!sheet['!cols'][index])
    {
      sheet['!cols'][index] = { wch: colWidth }
    }
  })
  utils.book_append_sheet(workBook, sheet, filename)
  writeFile(workBook, `${filename}.xlsx`)
  console.log('exportTableToExcel')
}
